package com.zhiche.lisa.bms.service.psup.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.zhiche.lisa.bms.dao.mapper.psup.PsupPriceRateMapper;
import com.zhiche.lisa.bms.dao.model.psup.PsupPriceRate;
import com.zhiche.lisa.bms.pojo.vo.psup.PsupPriceRateVO;
import com.zhiche.lisa.bms.service.psup.PsupPriceRateService;
import com.zhiche.lisa.bms.utils.ToolCommonUtils;
import com.zhiche.lisa.core.supports.BaseException;
import com.zhiche.lisa.core.utils.Account.AccountUtil;
import com.zhiche.lisa.core.utils.Account.JwtAccountVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * <p>
 * 人送供方一口价 服务实现类
 * </p>
 *
 * @author linbao
 * @since 2019-06-18
 */
@Service
@Slf4j
public class PsupPriceRateServiceImpl extends ServiceImpl<PsupPriceRateMapper, PsupPriceRate> implements PsupPriceRateService {

    /**
     * 人送价格比例的分页查询
     *
     * @param page
     * @return
     */
    @Override
    public Page<PsupPriceRateVO> querySdPriceRatePage(Page<PsupPriceRate> page) {
        EntityWrapper<PsupPriceRate> ew = this.buildCondition(page.getCondition());
        List<PsupPriceRate> psupPriceRateList = baseMapper.selectPage(page, ew);
        Page<PsupPriceRateVO> voPage = new Page<>();
        BeanUtils.copyProperties(page, voPage);
        if (CollectionUtils.isNotEmpty(psupPriceRateList)) {
            List<PsupPriceRateVO> voList = Lists.newArrayList();
            psupPriceRateList.forEach(priceRate -> {
                PsupPriceRateVO vo = new PsupPriceRateVO();
                BeanUtils.copyProperties(priceRate, vo);
                voList.add(vo);
            });
            voPage.setRecords(voList);
        }
        return voPage;
    }

    /**
     * 新增
     *
     * @param psupPriceRateVO
     */
    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public void createPriceRate(PsupPriceRateVO psupPriceRateVO) {
        this.verifyParam(psupPriceRateVO);
        // 校验时间是否冲突
        Integer count = this.counteVerifyDataIsExist(psupPriceRateVO);
        if (count > 0) {
            throw new BaseException("同一车队的浮动价格类型时间冲突!");
        }
        PsupPriceRate insertPriceRate = new PsupPriceRate();
        BeanUtils.copyProperties(psupPriceRateVO, insertPriceRate);
        insertPriceRate.setGmtCreate(new Date());
        JwtAccountVO account = AccountUtil.getAccountInfoFromSecurityContext();
        // 2019-10-30 创建人
        insertPriceRate.setCreatorName(account.getUsername());
        this.insert(insertPriceRate);
    }

    /**
     * 获取对应的价格比例设置
     *
     * @param psupPriceRate
     * @return
     */
    @Override
    public PsupPriceRate queryMatchRulePriceRate(PsupPriceRate psupPriceRate) {
        EntityWrapper<PsupPriceRate> ew = new EntityWrapper<>();
        ew.eq("fleet_id", psupPriceRate.getFleetId());
        if (Objects.nonNull(psupPriceRate.getEffectiveDate())) {
            ew.le("effective_date", ToolCommonUtils.getDateToStrFormat(psupPriceRate.getEffectiveDate()));
        }
        if (Objects.nonNull(psupPriceRate.getEffectiveDate())) {
            ew.ge("invalid_date", ToolCommonUtils.getDateToStrFormat(psupPriceRate.getEffectiveDate()));
        }
        List<PsupPriceRate> psupPriceRateList = this.selectList(ew);
        if (CollectionUtils.isNotEmpty(psupPriceRateList)) {
            return psupPriceRateList.get(0);
        }
        return null;
    }

    /**
     * 校验规则是否冲突
     *
     * @param psupPriceRate
     * @return
     */
    private Integer counteVerifyDataIsExist(PsupPriceRateVO psupPriceRate) {
        Map<String, Object> condition = Maps.newHashMap();
        if (Objects.nonNull(psupPriceRate.getEffectiveDate())) {
            condition.put("effectiveDate", new DateTime(psupPriceRate.getEffectiveDate()).toString(ToolCommonUtils.yyyyMMdd));
        }
        if (Objects.nonNull(psupPriceRate.getInvalidDate())) {
            condition.put("invalidDate", new DateTime(psupPriceRate.getInvalidDate()).toString(ToolCommonUtils.yyyyMMdd));
        }
        condition.put("fleetId", psupPriceRate.getFleetId());
        condition.put("notEqId", psupPriceRate.getId());
        return baseMapper.verifyIsExistDate(condition);
    }

    /**
     * 校验数据是否存在
     *
     * @param psupPriceRateVO
     */
    private void verifyParam(PsupPriceRateVO psupPriceRateVO) {
        if (Objects.isNull(psupPriceRateVO)) {
            throw new BaseException("参数为空!");
        }
        // 车队信息
        if (Objects.isNull(psupPriceRateVO.getFleetId()) || StringUtils.isBlank(psupPriceRateVO.getFleetName())) {
            throw new BaseException("车队信息为空!");
        }
        // 浮动的价格类型
        if (Objects.isNull(psupPriceRateVO.getFloatPriceType())) {
            throw new BaseException("浮动价格类型为空");
        }
        // 浮动比例
        if (Objects.isNull(psupPriceRateVO.getFloatRate())) {
            throw new BaseException("浮动比例为空");
        }
        // 生效时间
        if (Objects.isNull(psupPriceRateVO.getEffectiveDate())) {
            throw new BaseException("生效时间为空!");
        }
        // 失效时间
        if (Objects.isNull(psupPriceRateVO.getInvalidDate())) {
            throw new BaseException("失效时间为空!");
        }
        if (psupPriceRateVO.getEffectiveDate().compareTo(psupPriceRateVO.getInvalidDate()) > 0) {
            throw new BaseException("有效时间大于失效时间");
        }
    }

    /**
     * 查询条件
     *
     * @param condition
     * @return
     */
    private EntityWrapper<PsupPriceRate> buildCondition(Map<String, Object> condition) {
        EntityWrapper<PsupPriceRate> ew = new EntityWrapper<>();
        ew.orderBy("id desc");
        if (Objects.nonNull(condition)) {
            // 车队
            Object fleetId = condition.get("fleetId");
            if (Objects.nonNull(fleetId) && StringUtils.isNotBlank(fleetId.toString())) {
                ew.eq("fleet_id", fleetId);
            }
            Object fleetName = condition.get("fleetName");
            if (Objects.nonNull(fleetName) && StringUtils.isNotBlank(fleetName.toString())) {
                ew.eq("fleet_name", fleetName);
            }
            // 时间
            Object effectiveDateObj = condition.get("effectiveDate");
            if (Objects.nonNull(effectiveDateObj) && StringUtils.isNotBlank(effectiveDateObj.toString())) {
                Date effectiveDate = ToolCommonUtils.getDateByStr(effectiveDateObj.toString(), ToolCommonUtils.yyyyMMdd);
                ew.le("effective_date", effectiveDate);
                ew.ge("invalid_date", effectiveDate);
            }
            // 浮动类型
            Object floatPriceType = condition.get("floatPriceType");
            if (Objects.nonNull(floatPriceType) && StringUtils.isNotBlank(floatPriceType.toString())) {
                ew.eq("float_price_type", floatPriceType);
            }
        }
        return ew;
    }
}
